<?php
	
	/**
	 * Process a image uploaded via POST and resizes it 
	 * to the $maxAllowedSize.
	 * @param Integer $maxAllowedSize
	 * @param String $directory
	 * @param String $thumbDirectory
	 * @param Integer $thumbWidth
	 * @param String $name
	 * @param String $formName
	 * @param Array $allowedFormats
	 * 
	 * @return 0 	No picture uploaded
	 * @return -1	Invalid format
	 * @return -2 	Fatal Error
	 */
	function processImage(	$maxAllowedSize, 
												$directory, 
												$thumbDirectory,
												$thumbWidth, 
												$name, $formName, 
												$allowedFormats){	
		if(is_uploaded_file($_FILES[$formName]["tmp_name"])){
			$tmpName = $_FILES[$formName]["tmp_name"];
			$tmpFormat = str_replace("image/", "", $_FILES[$formName]["type"]);
			$format = "";
			$directoryAddition = substr(md5(time()), 0, 2);
			$directory .= "/".$directoryAddition;
			$thumbDirectory .= "/".$directoryAddition;
			
			/* Check the picture format */
			if(!is_array($allowedFormats)){
				$allowedFormats = array("jpeg", "jpg", "pjpeg", "pjpg", "png");		
			}
			
			foreach($allowedFormats as $allowedFormat){
				if(strcasecmp($tmpFormat, $allowedFormat) == 0)
					$format = $allowedFormat;
			}
			if(strlen($format) > 0){
				/* Format is valid */
				$format = str_replace("pjp", "jp", $format);	/* Fix */
				
				$imageName = $name.".".$format;
				$img = getimagesize($tmpName);
				if($img[0] <= $maxAllowedSize && $img[1] <= $maxAllowedSize){
					/* Dimensions are valid, upload it */					
					$thumbSizes = generateThumb($thumbDirectory, $thumbWidth, $name, $tmpName, $format);					
					createDirectory($directory);
					move_uploaded_file($tmpName, $directory."/".$imageName);	
					$ret = storePicture($name, $format, $directory, $thumbDirectory, array($img[0], $img[1]), $thumbSizes);	
					return $ret;
				}elseif($img[0] > $maxAllowedSize && $img[1] <= $maxAllowedSize){
					/* Width is bigger than the max allowed size */
					$newHeight = ceil($maxAllowedSize * $img[1] / $img[0]);
					$newWidth = $maxAllowedSize;
					$destination = imagecreatetruecolor($newWidth, $newHeight);
					$source = imageCreateGeneric($format, $tmpName);
					if($source){
						imagecopyresampled($destination, $source, 0, 0, 0, 0, $newWidth, $newHeight, $img[0], $img[1]);
						if(imageGeneric($format, $directory, $imageName, $destination)){
							$thumbSizes = generateThumb($thumbDirectory, $thumbWidth, $name, $tmpName, $format);
							$ret = storePicture($name, $format, $directory, $thumbDirectory, array($newWidth, $newHeight), $thumbSizes);
							imagedestroy($destination);
							imagedestroy($source);
							return $ret;
						}else{
							return -2;
						}
					}else{
						imagedestroy($destination);
						return -2;
					}
				}elseif($img[0] <= $maxAllowedSize && $img[1] > $maxAllowedSize){
					/* Height is bigger than the max allowed size */
					$newHeight = $maxAllowedSize;
					$newWidth = ceil($maxAllowedSize * $img[0] / $img[1]);
					$destination = imagecreatetruecolor($newWidth, $newHeight);
					$source = imageCreateGeneric($format, $tmpName);
					if($source){
						imagecopyresampled($destination, $source, 0, 0, 0, 0, $newWidth, $newHeight, $img[0], $img[1]);
						if(imageGeneric($format, $directory, $imageName, $destination)){
							$thumbSizes = generateThumb($thumbDirectory, $thumbWidth, $name, $tmpName, $format);
							$ret = storePicture($name, $format, $directory, $thumbDirectory, array($newWidth, $newHeight), $thumbSizes);
							imagedestroy($destination);
							imagedestroy($source);
							return $ret;
						}else{
							return -2;
						}
					}else{
						imagedestroy($destination);
						return -2;
					}
				}elseif($img[0] > $maxAllowedSize && $img[1] > $maxAllowedSize){
					/* Both are bigger than the max allowed size */
					if($img[0] >= $img[1]){
						/*  Width is bigger */
						$newWidth = $maxAllowedSize;
						$newHeight = ceil($maxAllowedSize * $img[1] / $img[0]);
						$destination = imagecreatetruecolor($newWidth, $newHeight);
						$source = imageCreateGeneric($format, $tmpName);
						if($source){
							imagecopyresampled($destination, $source, 0, 0, 0, 0, $newWidth, $newHeight, $img[0], $img[1]);
							if(imageGeneric($format, $directory, $imageName, $destination)){
								$thumbSizes = generateThumb($thumbDirectory, $thumbWidth, $name, $tmpName, $format);
								$ret = storePicture($name, $format, $directory, $thumbDirectory, array($newWidth, $newHeight), $thumbSizes);
								imagedestroy($destination);
								imagedestroy($source);
								return $ret;
							}else{
								return -2;
							}
						}else{
							imagedestroy($destination);
							return -2;
						}
					}else{
						/* Height is bigger */
						$newHeight = $maxAllowedSize;
						$newWidth = ceil($maxAllowedSize * $img[0] / $img[1]);
						$destination = imagecreatetruecolor($newWidth, $newHeight);
						$source = imageCreateGeneric($format, $tmpName);
						if($source){
							imagecopyresampled($destination, $source, 0, 0, 0, 0, $newWidth, $newHeight, $img[0], $img[1]);
							if(imageGeneric($format, $directory, $imageName, $destination)){
								$thumbSizes = generateThumb($thumbDirectory, $thumbWidth, $name, $tmpName, $format);
								$ret = storePicture($name, $format, $directory, $thumbDirectory, array($newWidth, $newHeight), $thumbSizes);
								imagedestroy($destination);
								imagedestroy($source);
								return $ret;
							}else{
								return -2;
							}
						}else{
							imagedestroy($destination);
							return -2;
						}
					}
				}
			}else{
				/* Format is invalid */
				return -1;
			}
		}else{
			return 0;
		}
	}
	
	function imageCreateGeneric($format, $name){
		switch($format){
			case "jpeg":
			case "jpg":
			case "pjpeg": 
			case "pjpg":	return imagecreatefromjpeg($name);
			
			case "png": 	return imagecreatefrompng($name);
			case "gif": 		return imagecreatefromgif($name);
			default: 			return FALSE;
		}
	}
	
	function imageGeneric($format, $directory, $name, $resource){		
		createDirectory($directory);
		switch($format){
			case "jpeg":
			case "jpg":
			case "pjpeg": 
			case "pjpg":	return imagejpeg($resource, $directory."/".$name);
			
			case "png": 	return imagepng($resource, $directory."/".$name);
			case "gif": 		return imagegif($resource, $directory."/".$name);
			default: 			return FALSE; 
		}
	}
	
	function generateThumb($directory, $thumbWidth, $name, $tmpName, $format){
		if(is_uploaded_file($tmpName)){
			$img = getimagesize($tmpName);
			$newHeight = $thumbWidth * $img[1] / $img[0];
			$source = imageCreateGeneric($format, $tmpName);
			$destination = imagecreatetruecolor($thumbWidth, $newHeight);
			imagecopyresampled($destination, $source, 0, 0, 0, 0, $thumbWidth, $newHeight, $img[0], $img[1]);
			createDirectory($directory);			
			imagejpeg($destination, $directory."/".$name.".jpg");
			imagedestroy($source);
			imagedestroy($destination);
			return array($thumbWidth, $newHeight);
		}else{
			return FALSE;
		}
	}
	
	function storePicture($name, $format, $directory, $thumbDirectory, $pictureSizes, $thumbSizes){
		$picturePath = $directory."/".$name.".".$format;
		$thumbPath = $thumbDirectory."/".$name.".jpg";
		$query = new mysqlQuery("tournament", "", "image", "*", "`picture_path` = '".$picturePath."'", "", "");
		$query->execute();
		if($query->getCount() == 0){
			$values = array(NULL, $picturePath, $thumbPath, $pictureSizes[0], $pictureSizes[1], $thumbSizes[0], $thumbSizes[1]);
			$insert = new mysqlInsert("tournament", "", "image", $values);
			$insert->execute();
			return $insert->getInsertedId();
		}else{
			return 0;
		}
	}
	
	function createDirectory($directoryName){
		if(!is_dir($directoryName)){
			mkdir($directoryName);
		}
	}

?>